# -*- coding: utf-8 -*-
# @project: test06.py
# @file： yk_applets_api.py
# @Time：2023/7/3 16:44
# @Author：liaogan
import json
import random

import allure
import os, time
from common.commin.commin import read_ini, show_time
from common.request.request_api import YkRequestHandler
from config.conf import BASE_DIR
from common.log.log import log
from random import randint

print()
# 生产环境url
url = read_ini(BASE_DIR + '/config_yk.ini')['host']['url']
print(url)
usertoken = read_ini(BASE_DIR + '/config_yk.ini')['host']['usertoken']


class YK_Applets_api():
    def __init__(self):
        self.url = url

    @allure.step("获取商品详情")
    def get_product_details(self, data=False):
        """
        获取商品详情
        """
        try:
            log.info('api接口获取商品详情')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + f'/apiserver/api/product/detail/90?latitude=&longitude='
            response = req.visit('get', get_url)
            if data:
                """商品ID ，购物车唯一标识ID"""
                productId = response.json()["data"]['productAttr'][0]['productId']
                unique = response.json()["data"]['productValue']['默认']['unique']

                return productId, unique
            else:
                return response.text
        except Exception as e:
            log.error(f'api接口花王云客获取商品详情接口出现异常为：{e}')
            raise e

    @allure.step("将商品加入到购物车")
    def add_product_cart(self, productId, unique):
        """
        将商品加入到购物车
        """
        try:
            log.info('api接口商品加入到购物车')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + f'/apiserver/api/cart/add'
            payload = {"productId": "{}".format(productId), "cartNum": 1, "new": 0, "uniqueId": "{}".format(unique)}
            response = req.visit('post', get_url, json=payload)
            return response.text
        except Exception as e:
            log.error(f'api接口花王云客商品加入到购物车接口出现异常为：{e}')
            raise e

    @allure.step("获取购物车商品列表操作")
    def get_Cart_product_list(self, ID=False):
        """
        获取购物车商品列表
        """
        try:
            log.info('api接口花王云客获取商品列表')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + f'/apiserver/api/cart/list'
            response = req.visit('get', get_url, )
            if ID:
                return response.json()['data']['valid'][0]['id']
            else:
                return response.text
        except Exception as e:
            log.error(f'api接口花王云客获取商品列表接口出现异常为：{e}')
            raise e

    @allure.step("设置购物车商品")
    def set_Cart_num(self, ID):
        """
        设置购物车商品数量
        """
        try:
            log.info('api接口花王云客设置购物车商品数量')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/cart/num'
            payload = {"id": ID, "number": randint(1, 3)}
            response = req.visit('post', get_url, json=payload)
            return response.text
        except Exception as e:
            log.error(f'api接口花王云客设置购物车商品数量出现异常为：{e}')
            raise e

    @allure.step("删除购物车商品")
    def del_Cart_product(self, ID):
        """
        删除购物车商品
        """
        try:
            log.info('api接口花王云客删除购物车商品')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/cart/del'
            payload = {"ids": [ID]}
            response = req.visit('post', get_url, json=payload)
            return response.text
        except Exception as e:
            log.error(f'api接口花王云客删除购物车商品出现异常为：{e}')
            raise e

    @allure.step("花王云客签到")
    def sign_in(self):
        """
        签到
        """
        try:
            log.info('api接口花王云客签到操作')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/sign/integral'
            payload = {}
            response = req.visit('post', get_url, json=payload)
            return response.text
        except Exception as e:
            log.error(f'api接口花王云客签到出现异常为：{e}')
            raise e

    @allure.step("我的足迹")
    def my_footmark(self, pid=False):
        """
        我的足迹
        """
        pid_list = []
        try:
            log.info('api接口花王云客我的足迹')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/collect/user?page=1&limit=20&type=foot'
            response = req.visit('get', get_url)
            if pid:
                data = json.loads(response.text)["data"]
                # for one in data:
                #     pid_list.append(one['pid'])
                return data

            else:
                return response.text

        except Exception as e:
            log.error(f'api接口花王云客我的足迹出现异常为：{e}')
            raise e

    @allure.step("删除我的足迹")
    def del_my_footmark(self, pid):
        """
        删除我的足迹
        """
        try:
            log.info('api接口花王云客删除我的足迹')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/collect/del'
            payload = {"id": pid, "category": "foot"}
            response = req.visit('post', get_url, json=payload)
            return response.text
        except Exception as e:
            log.error(f'api接口花王云客删除我的足迹出现异常为：{e}')
            raise e

    @allure.step("获取我的收货地址")
    def get_my_address(self):
        """获取我的收货地址"""
        try:
            log.info('api接口花王云客获取收货地址')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/address/list?page=1&limit=20'
            response = req.visit('get', get_url)
            return response.text
        except Exception as e:
            log.error(f'api接口花王云客获取收货地址出现异常为：{e}')
            raise e

    @allure.step('编辑收货地址')
    def edit_address(self, edit):
        randomlist_name = ['liaogan', '廖干', 'liaog']
        name = random.choice(randomlist_name)
        """编辑收货地址"""
        try:
            log.info('花王云客api接口-编辑收货地址')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/address/edit'
            payload = {"id": "{}".format(edit),
                       "real_name": f"{name}{randint(00, 99)}",
                       "phone": "13636106842",
                       "address": {"province": "广东省", "city": "深圳市", "district": "福田区", "city_id": 487721},
                       "detail": "能源大厦1504", "is_default": "true", "post_code": ""}

            response = req.visit('post', get_url, json=payload)
            return response.text
        except Exception as e:
            log.error(f'花王云客api接口-添加收货地址出现异常为：{e}')
            raise e

    @allure.step('添加收货地址')
    def add_address(self):
        """添加收货地址"""
        try:
            log.info('花王云客api接口-添加收货地址')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/address/edit'
            payload = {"real_name": f"廖干{randint(00, 99)}",
                       "phone": "13636105588",
                       "address": {"province": "广东省", "city": "深圳市", "district": "福田区", "city_id": 487721},
                       "detail": f"能源大厦15{randint(00, 99)}", "is_default": "true", "post_code": ""}

            response = req.visit('post', get_url, json=payload)
            return response.text
        except Exception as e:
            log.error(f'花王云客api接口-添加收货地址出现异常为：{e}')
            raise e

    @allure.step('删除收货地址')
    def delete_address(self, deleteID):
        """删除收货地址"""
        try:
            log.info('花王云客api接口-删除收货地址')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/address/del'
            payload = {"id": deleteID}

            response = req.visit('post', get_url, json=payload)
            return response.text
        except Exception as e:
            log.error(f'花王云客api接口-添加收货地址出现异常为：{e}')
            raise e

    @allure.step('添加商品收藏')
    def add_collect(self):
        """添加商品收藏
        这里固定写死，商品id为91，嘛嘛达达.清形米酒（柚子味）375Ml（1瓶）
        """
        try:
            log.info('花王云客api接口-添加商品收藏')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/collect/add'
            payload = {"id": 91, "category": "collect"}

            response = req.visit('post', get_url, json=payload)
            return response.text
        except Exception as e:
            log.error(f'花王云客api接口-添加收货地址出现异常为：{e}')
            raise e

    @allure.step('获取商品收藏')
    def get_collect(self):
        """
        获取收藏商品
        """
        try:
            log.info('花王云客api接口-获取商品收藏')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/collect/user?page=1&limit=20&type=collect'
            response = req.visit('get', get_url)
            # return json.loads(response.text)
            return response.text

        except Exception as e:
            log.error(f'花王云客api接口-获取商品收藏出现异常为：{e}')
            raise e

    @allure.step('删除收藏商品')
    def delete_collect(self, pid):
        """删除收藏商品"""
        try:
            log.info('花王云客api接口-删除收藏商品')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/collect/del'

            payload = {"id": pid, "category": "collect"}

            response = req.visit('post', get_url, json=payload)
            return response.text


        except Exception as e:
            log.error(f'花王云客api接口-添加收货地址出现异常为：{e}')
            raise e

    @allure.step('修改用户昵称')
    def edit_nickname(self):
        """修改用户昵称"""

        list_name = ['Super_liao', 'jaychou', 'liaog']
        nickname = random.choice(list_name)
        naickname_num = nickname + str(randint(000, 999))
        try:
            log.info('花王云客api接口-修改用户昵称')
            req = YkRequestHandler(usertoken, 'yk')
            get_url = self.url + '/apiserver/api/user/edit'

            payload = {"nickname": "{}".format(naickname_num),
                       "avatar": "https://jky.huawangglobal.com/upload/1681955477887微信图片_20230420095103.jpg"}

            response = req.visit('post', get_url, json=payload)
            return response.json()

        except Exception as e:
            log.error(f'花王云客api接口-修改用户昵称出现异常为：{e}')
            raise e


from functools import wraps


def Showtime(fun):
    @wraps(fun)
    def localtime(*args, **kwargs):
        start = time.time()
        res = fun(*args, **kwargs)
        end = time.time()
        slaps = end - start
        log.info('花王云客小程序接口自动化用例运行时间为:%.6f' % slaps)
        return res

    return localtime


if __name__ == '__main__':
    res = YK_Applets_api()

    # 查看商品详情
    # print(res.get_product_details())
    # productId, unique = res.get_product_details(data=True)
    # print(productId, unique)
    # #
    # #将商品加入购物车
    # print(res.add_product_cart(productId, unique))
    #
    # #获取购物车商品列表
    ID = res.get_Cart_product_list(ID=False)
    print(json.loads(ID)['data']['valid'])
    # print(json.loads(ID)['data']['valid'][0]['id'])
    # #
    # #设置购物车数量
    # res.set_Cart_num(ID)
    #
    # # 删除购物车商品
    # res.del_Cart_product(ID)

    # 签到操作
    # print(res.sign_in())

    # 我的足迹
    # pid = res.my_footmark(pid=True)

    # 删除我的足迹
    # print(res.del_my_footmark(pid))

    # 获取收货地址
    # print(res.get_my_address())
    # addressID = res.get_my_address()['data'][0]['id']
    # print(addressID)

    # 修改收货地址信息
    # respone = res.edit_address(addressID)
    # print(respone)

    # 新增收货地址
    # res=res.add_address()
    # print(res)
    # 删除收货地址
    # respone=res.delete_address(addressID)
    # print(respone)

    # 商品收藏
    # res = res.add_collect()
    # print(res)

    # 获取收藏商品
    # pid=res.get_collect()['data'][0]['pid']
    # pid=int(pid)
    # print(pid)

    # 删除收藏的商品
    # res=res.delete_collect(pid)
    # print(res)

    # res=res.edit_nickname()
    # print(res)
